﻿using OneWorks.Web.Extension;

namespace OneWorks.Web.Common
{
    using System;
    using Model;

    using OneWorks.Metadata.Enum;

    public class UserContext
    {
        private readonly UserHandle _userHandle = new UserHandle();

        public UserContext()
        {
            Initialization();
        }

        public void Initialization()
        {
            string value = Cookie.GetCookie(Config.COOKIENAME);
            if (string.IsNullOrEmpty(value))
            {
                Current = new UserModel();
            }
            else
            {
                Guid userCode = Guid.Parse(Utils.Tools.DESDecrypt(value, Config.COOKIEKEY));
                Metadata.Entity.RunResult<UserModel> runResult = _userHandle.GetUserInfo(userCode);
                Current = runResult.Status != ResultStatus.Success ? new UserModel() : runResult.Result;
                Cookie.SetCookie(Config.COOKIENAME,
                    Utils.Tools.DESDecrypt(Current.UserCode.ToString().ToLower(), Config.COOKIEKEY),"/");
            }
            if (Current.UserCode != Guid.Empty)
                IsLogin = true;
        }

        public bool IsLogin { get; private set; }

        public UserModel Current { get; private set; }
    }
}
